package iosr11.Service;

import iosr11.contact.dao.ContactsHelper;
import iosr11.data.Teacher;
import iosr11.data.User;
import iosr11.gbase.dao.TeacherDAO;

import java.util.List;
import java.util.logging.Logger;

public class TeacherServiceImpl implements TeacherService{

	private TeacherDAO teacherDAO;
	private ContactsHelper contactsDAO;
	private Logger log = Logger.getLogger("service-log");
	
	
	
	@Override
	public Class<Teacher> getServiceEntityClass() {
		return Teacher.class;
	}

	@Override
	public boolean createTeacher(String name, String email, boolean isLecturer) {
		if ((name==null)||(email==null)) return false;
		User user = new User(null, name, email);
		contactsDAO.addUser(user);
		Teacher teacher = new Teacher(user);
		teacher.setLecturer(isLecturer);
		return teacherDAO.add(teacher);
	}

	@Override
	public boolean deleteTeacher(Teacher teacher) {
		log.info("usuwanie nauczyciela: "+teacher.getName());
		return teacherDAO.delete(teacher);
	}

	@Override
	public boolean updateTeacher(Teacher teacher) {
		if (!contactsDAO.updateUser(teacher.getUser())){
			log.warning("nie mozna uaktualnic danych kontaktu dla nauczyciela");
			return false;
		}
		if (!teacherDAO.update(teacher)){
			log.warning("nie mozna uaktualnic rekordu w bazie z danymi nauczyciela");
			return false;
		}
		return true;
	}

	@Override
	public Teacher getTeacher(String login) {
		/*Pobranie danych usera (nazwisko, email, id w kontaktach)*/
		User user = new User();
		user = contactsDAO.getUser(login);
		if (user == null) return null;
		
		/*Pobranie dodatkowych danych nauczyliela (isLecturer, id w bazie)*/
		Teacher teacher = teacherDAO.getByUserRef(user.getId());
		if (teacher==null) return null;
		teacher.setUser(user);
		
		return teacher;
	}
	
	@Override
	public List<Teacher> getAllTeachers() {
		// TODO Auto-generated method stub
		List<Teacher> teachers = teacherDAO.getAll();
		if (teachers == null){
			log.warning("brak rekordow w bazie - brak nauczycieli (null)");
			return null;
		}/*
		else if (teachers.size() < 1){
			log.warning("brak rekordow w bazie - brak nauczycieli (size<1)");
			return null;
		}*/
		int i=0;
		while(i<teachers.size()){
			Teacher teacher = teachers.get(i);
			if (teacher==null){
				teachers.remove(i);
			}
			else {
				User user = contactsDAO.getUserByRef(teacher.getUser().getId());
				if (user!=null) {
					teacher.setUser(user);
					i++;
				}
				else {
					log.warning("brak kontaktu do wpisu w bazie");
					teachers.remove(i);
				}
			}
		}
		
		return teachers;
	}

	// =================================================================
	// getery i settery uzywane do springa
	
	public TeacherDAO getTeacherDAO() {
		return teacherDAO;
	}

	public void setTeacherDAO(TeacherDAO teacherDAO) {
		this.teacherDAO = teacherDAO;
	}

	public ContactsHelper getContactsDAO() {
		return contactsDAO;
	}

	public void setContactsDAO(ContactsHelper contactsDAO) {
		this.contactsDAO = contactsDAO;
	}
}
